package com.hu.aspect;

import com.hu.annotation.HotKeyCacheable;
import com.jd.platform.hotkey.client.callback.JdHotKeyStore;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@Component
@Aspect
public class HotKeyAspect {

    private final ExpressionParser parser = new SpelExpressionParser();

    @Around("@annotation(hotKeyCacheable)")
    public Object logAround(ProceedingJoinPoint joinPoint, HotKeyCacheable hotKeyCacheable) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        EvaluationContext context = new StandardEvaluationContext(joinPoint.getThis());
        for (int i = 0; i < method.getParameterCount(); i++) {
            context.setVariable(method.getParameters()[i].getName(), joinPoint.getArgs()[i]);
        }
        String keyExpression = hotKeyCacheable.key();
        String key = (String) parser.parseExpression(keyExpression).getValue(context);
        // 前缀
        String prefix = hotKeyCacheable.prefix();
        String hotKey = prefix + key;
        Object infoFromCache = JdHotKeyStore.getValue(hotKey);
        Object infoFromDb;
        if (infoFromCache == null) {
            infoFromDb = joinPoint.proceed();
            JdHotKeyStore.smartSet(hotKey, infoFromDb);
            return infoFromDb;
        } else {
            //使用缓存好的value即可
            return infoFromCache.toString();
        }
    }
}
